<template>
  <div>
    <div style="text-align: left; margin: 10px">
      <el-button size="mini" type="primary" @click="toAdd">
        添加
      </el-button>
      <el-select v-model="searchParams.dorm"
                 placeholder="选择楼舍"
                 size="mini"
                 :disabled="!searchParams"
                 @change="changeDorm"
                 style="margin-left: 10px">
        <el-option
                v-for="item in dorms"
                :key="item"
                :label="item"
                :value="item">
        </el-option>
      </el-select>
      <el-input type="text"
                style="width: 200px; margin: 0px 5px;"
                placeholder="寝室房间号"
                size="mini"
                :disabled="!searchParams || !searchParams.dorm"
                v-model="searchParams.room" clearable>
      </el-input>

      <el-button size="mini" @click="clearSearchParams">
        清空
      </el-button>
      <el-button size="mini" type="primary" @click="search">
        查询
      </el-button>
    </div>

    <!--增加或更新的表单弹窗-->
    <el-dialog :title=formTitle :visible.sync="formDialogVisible">
      <el-form ref="form" :model="formData" :rules="rules" size="large" label-width="100px">
        <el-form-item label="选择楼舍" style="text-align: left;" v-if="formTitle !== '添加'">
          <el-select v-model="formData.dorm"
                     placeholder="选择楼区"
                     size="mini"
                     style="margin-left: 10px">
            <el-option
                    v-for="item in dorms"
                    :key="item"
                    :label="item"
                    :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼舍" v-if="formTitle === '添加'" style="text-align: left;">
          <el-input v-model="formData.dorm" placeholder="楼舍"></el-input>
        </el-form-item>
        <el-form-item label="寝室" prop="room">
          <el-input v-model="formData.room" placeholder="房间号"></el-input>
        </el-form-item>
        <el-form-item label="水票价格" prop="waterPrice" style="text-align: left;">
          <el-input-number v-model="formData.waterPrice" :min="0" :max="100"></el-input-number>
          元
        </el-form-item>
        <el-form-item label="房间水桶" prop="bucketNum" style="text-align: left;">
          <el-input-number v-model="formData.bucketNum" :min="0" :max="10"></el-input-number>
          桶
        </el-form-item>
        <el-form-item label="剩余水票" prop="oweTicketNum" style="text-align: left;">
          <el-input-number v-model="formData.ticketNum" :min="0" :max="1000"></el-input-number>
          张
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="handelConfirm">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--列表-->
    <div style="margin: 10px;text-align: left;">
      <el-table :data="addresses"
                stripe
                :default-sort="{prop: 'room', order: 'inc'}">

        <el-table-column prop="dorm" label="楼舍" sortable></el-table-column>
        <el-table-column prop="room" label="寝室" sortable></el-table-column>
        <el-table-column label="叫水状态">
          <template slot-scope="scope">
            <el-switch
                    v-model="scope.row.taskStatus"
                    active-color="green"
                    inactive-color="red"
                    @change="(value) => commitStatusChange(value, scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="waterPrice" label="水票价格(元)"></el-table-column>
        <el-table-column prop="bucketNum" label="房间水桶(桶)" sortable></el-table-column>
        <el-table-column prop="ticketNum" label="剩余水票(张)" sortable></el-table-column>
        <el-table-column prop="lastTime" label="上次换水" show-overflow-tooltip sortable></el-table-column>

        <el-table-column label="操作"  width="170">
          <template slot-scope="scope">
            <el-button @click="showRoomMembers(scope.row.id)" type="text" size="mini">寝室成员</el-button>
            <el-button @click="toEdit(scope.row)" type="text"  size="mini">编辑</el-button>
            <el-button type="text"  size="mini" @click="toDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-row style="float: right">
        <el-pagination
                @current-change="changePageNo"
                @size-change="changePageSize"
                :current-page.sync="searchParams.pageNo"
                :page-sizes="[5, 10, 20, 30, 50, 100]"
                :page-size.sync="searchParams.pageSize"
                layout=" total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>
      </el-row>
    </div>

    <!--寝室成员-->
    <el-dialog title="寝室成员" :visible.sync="showRoomMembersDialog">
      <el-row align="center" style="display: flex; justify-content: space-around; border-bottom: 1px solid #e2e2e7">
        <div>学号</div>
        <div>姓名</div>
      </el-row>
      <el-row align="center" v-for="(item, index) in roomMembers" :key="index"
              style="display: flex; justify-content: space-between;border-bottom: 1px solid #e2e2e7">
        <div>{{item.student_no}}</div>
        <div>{{item.name}}</div>
        <el-button type="danger" size="mini" @click="removeMember(item)">移除</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addAddress,
    deleteAddresss,
    getAddressesByConditions,
    getDormList,
    getRoomsOfDorm,
    updateAddress,
    changeTaskStatus
  } from "../../../api/modules/app/addressApi";
  import {getMembersOfAddress, removeAddressOfStudent} from "../../../api/modules/app/studentApi";

  export default {
    name: "addressComponent",
    data() {
      return {
        currentPage: 1,
        pageSize: 10,
        addresses: [],
        formDialogVisible: false,
        showRoomMembersDialog: false, // 寝室成员列表
        formTitle: '添加',
        formData: {
          id: null,
          dorm: null,
          room: null,
          taskStatus: false,
          waterPrice: 13,
          bucketNum: 0,
          ticketNum: 0,
          lastTime: null
        },
        dorms: ['二区15舍'],
        rooms: [],
        // 查询参数
        searchParams: {
          dorm: null,
          room: null,
          pageNo: 1,
          pageSize: 10
        },
        total: 0,
        rules: {
          dorm: [
            {required: true, message: '不能为空', trigger: 'blur'}
          ], room: [
            {required: true, message: '不能为空', trigger: 'blur'}
          ], waterPrice: [
            {required: true, message: '水票价格不能为空', trigger: 'blur', type: "number"}
          ], bucketNum: [
            {required: true, message: '房间水桶数不能为空', trigger: 'blur', type: "number"}
          ], ticketNum: [
            {required: true, message: '剩余水票数不能为空', trigger: 'blur', type: "number"}
          ]
        },
        roomMembers: [] // 寝室成员
      }
    },
    created(){
      this.getAllDormList();
      this.search()
    },
    methods: {
      getAllDormList() {
        let that = this;
        // 所有楼舍
        getDormList().then(result => {
          that.dorms = result.data;
          that.searchParams.dorm = null;
          that.searchParams.room = null;
          that.search();
        })
      },
      // 切换楼舍
      changeDorm(dorm) {
        let that = this;
        // 获取楼区所有寝室
        getRoomsOfDorm(dorm).then(result => {
          that.rooms = result.data;
          that.searchParams.room = null;
          that.search();
        })
      },
      // 清除查询参数
      clearSearchParams() {
        this.searchParams = {
          dorm: null,
          room: null
        }
        this.search();
      },
      // 切换页数
      changePageNo(pageNo) {
        this.searchParams.pageNo = pageNo;
        this.search()
      },
      // 改变页面大小
      changePageSize(pageSize) {
        this.searchParams.pageSize = pageSize;
        this.search()
      },
      // 查询
      search() {
        getAddressesByConditions(this.searchParams).then(result => {
          this.addresses = result.data.records;
          this.total = result.data.total;
        })
      },
      // 改变叫水状态
      commitStatusChange(value, address) {
        this.$confirm(value === false ? '是否取消叫水?' : '是否叫水?', {
          type: 'primary'
        }).then(() => {
          changeTaskStatus(address.id).then(() => {
            this.$notify.success(value === false ? "已取消叫水" : "操作成功");
          }).catch(() => {
            address.taskStatus = !value;
          })
        }).catch(() => {
          address.taskStatus = !value;
        })
      },
      // 重置表单
      resetForm() {
        // 手动重置 不然数据被绑定在toEdit时深克隆出来的对象
        this.formData = {
          id: null,
          area: null,
          dorm: null,
          room: null,
          taskStatus: false,
          waterPrice: 13,
          bucketNum: 1,
          ticketNum: 0,
          lastTime: null
        }
      },
      // 添加
      toAdd() {
        this.resetForm()
        this.formDialogVisible = true
        this.formTitle = '添加'
      },
      // 删除
      toDelete(id) {
        let that = this;
        this.$confirm("是否删除").then(() => {
          deleteAddresss([id]).then(() => {
            this.$notify.success("删除成功");
            that.search();
          })
        }).catch(() => {
        })
      },
      // 编辑
      toEdit(selectedAddress) {
        // 深拷贝一个对象 不然在表格显示的数据会受到印象
        this.formData = JSON.parse(JSON.stringify(selectedAddress));
        this.formDialogVisible = true
        this.formTitle = '更新'
      },
      // 提交表单
      handelConfirm() {
        this.$refs['form'].validate(valid => {
          console.log(this.formTitle)
          if (!valid)
            return

          this.formDialogVisible = false;
          if (this.formTitle.startsWith('添加')) {
            addAddress(this.formData).then(result => {
              this.$notify({
                title: "添加成功",
                type: "success",
                duration: 1000
              });
              this.search()
            })
          } else if (this.formTitle.startsWith('更新')) {
            updateAddress(this.formData).then(result => {
              this.$notify({
                title: "更新成功",
                type: "success",
                duration: 1000
              });
              this.search()
            })
          }
        })
      },
      // 寝室成员
      showRoomMembers(addressId) {
        this.showRoomMembersDialog = true;
        getMembersOfAddress(addressId).then(result => {
          this.roomMembers = result.data;
        })
      },
      // 移除寝室成员
      removeMember(data) {
        this.$confirm("将" + data.name + "移出寝室?").then(() => {
          this.showRoomMembersDialog = false;
          removeAddressOfStudent(data.id).then(result => {
            this.$notify.success("已将" + data.name + "移出寝室");
          })
        }).catch(()=>{})
      }
    }
  }
</script>
